from treelib import Tree

class GenerateTree:

    ast_table_tree_list = []

    def generateTree(self,ast_table_list):
        tree = Tree()
        tree.create_node('Super', 'super')

        for i in range(len(ast_table_list)):
            firstname = 'Tree_' + str(i)
            secondname = 'tree_' + str(i)

            if ast_table_list[i].level == 0:
                tree.create_node(firstname,secondname,parent='super',data=ast_table_list[i])
                self.ast_table_tree_list.append({ast_table_list[i]:secondname})
            elif ast_table_list[i].level > ast_table_list[i-1].level:
                tree.create_node(firstname, secondname, parent=list(self.ast_table_tree_list[i-1].values())[0], data=ast_table_list[i])
                self.ast_table_tree_list.append({ast_table_list[i]:secondname})
            else:
                ast_level_tmp = ast_table_list[i].level
                for v_index in list(range(i))[::-1]:
                    if ast_table_list[v_index].level < ast_level_tmp:
                        tree.create_node(firstname, secondname, parent=list(self.ast_table_tree_list[v_index].values())[0],
                                         data=ast_table_list[i])
                        self.ast_table_tree_list.append({ast_table_list[i]:secondname})
                        break
        return tree